// Copyright (C) Kumo inc. and its affiliates.
// Author: Jeff.li lijippy@163.com
// All rights reserved.
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published
// by the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program.  If not, see <https://www.gnu.org/licenses/>.
//
/*
 * Copyright owned by the Transaction Processing Performance Council.
 *
 * A copy of the license is included under extension/tpch/dbgen/LICENSE
 * in this repository.
 *
 * You may not use this file except in compliance with the License.
 *
 * THE TPC SOFTWARE IS AVAILABLE WITHOUT CHARGE FROM TPC.
 */ /*
 * permute.c -- a permutation generator for the query
 *              sequences in TPC-H and TPC-R
 */

#include <pollux/tpch/gen/dbgen/config.h> // @manual
#include <pollux/tpch/gen/dbgen/dss.h> // @manual

namespace kumo::pollux::tpch::dbgen {
    DSS_HUGE NextRand(DSS_HUGE seed);

    void permute(long *set, int cnt, seed_t *seed);

    void permute_dist(distribution *d, seed_t *seed);

    long seed;
    char *eol[2] = {" ", "},"};

#define MAX_QUERY 22
#define ITERATIONS 1000
#define UNSET 0

    void permute(long *a, int c, seed_t *seed) {
        int i;
        static DSS_HUGE source;
        static long temp;

        if (a != reinterpret_cast<long *>(NULL)) {
            for (i = 0; i < c; i++) {
                RANDOM(source, static_cast<long>(i), static_cast<long>(c - 1), seed);
                temp = *(a + source);
                *(a + source) = *(a + i);
                *(a + i) = temp;
            }
        }

        return;
    }

    void permute_dist(distribution *d, seed_t *seed) {
        int i;

        if (d != NULL) {
            if (d->permute == reinterpret_cast<long *>(NULL)) {
                d->permute = reinterpret_cast<long *>(malloc(sizeof(long) * DIST_SIZE(d)));
                MALLOC_CHECK(d->permute);
            }
            for (i = 0; i < DIST_SIZE(d); i++)
                *(d->permute + i) = i;
            permute(d->permute, DIST_SIZE(d), seed);
        } else
        INTERNAL_ERROR("Bad call to permute_dist");

        return;
    }
} // namespace kumo::pollux::tpch::dbgen
